package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.CacheData;
import com.gable.common.util.ImportExcel;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.ContractService;
import com.gable.exhibition.util.CheckImportExcelContract;
import com.gable.exhibition.util.CheckImportExcelEstimate;
import com.gable.exhibition.util.CheckImportExcelHospital;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * Created by mj on 2018/1/4.
 */
@Controller
@RequestMapping(value = "/contract")
public class ContractController {

    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    ContractService contractService;

    @Autowired
    CheckImportExcelContract checkImportExcelContract;

    @Autowired
    CheckImportExcelEstimate checkImportExcelEstimate;

    @RequestMapping(value = "/page")
    public String page(HttpServletRequest request, HttpServletResponse response){
        return "contract/contract-page";
    }

    @RequestMapping(value="/info")
    public String info(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true) Long id){
        request.setAttribute("contractId",id);
        return "contract/contract-info";
    }

    /**
     * 合同列表
     * @param request
     * @return
     */
    @RequestMapping(value="/contractList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil contractList(HttpServletRequest request, ParameterView parameterView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        try {
            Long userId = parameterView.getUserId();
            UserView sessionUser = CacheData.getSessionUser(userId, 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);

            //医院登录
            if(sessionUser.getType().intValue() == 1101)
                parameterView.setHospitalId(sessionUser.getHospitalId());
            resultUtil = contractService.contractList(parameterView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    /**
     * 查询合同下需要发货的设备列表
     * @param request
     * @param parameterView
     * @return
     */
    @RequestMapping(value="/deviceByContract",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil deviceByContract(HttpServletRequest request, ParameterView parameterView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);

        try {
            Long contractId = parameterView.getContractId();
            if(contractId == null)
                return new ReturnResultUtil(500,MessageUtil.CONTRACTIDNOEXIST);
            resultUtil = contractService.deviceByContract(parameterView);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultUtil;
    }

    @RequestMapping(value="/queryContractInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryContractInfo(HttpServletRequest request){
        try {
            if (StringUtil.isEmpty(request.getParameter("contractId"))) {
                return new ReturnResultUtil(500, MessageUtil.CONTRACTIDNOEXIST);
            }

            Long id = Long.parseLong(request.getParameter("contractId"));
            ReturnResultUtil rru = contractService.querycontractInfo(id);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }

    @RequestMapping(value="/estimateQuantity",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil estimateQuantity(HttpServletRequest request){
        try {
            if (StringUtil.isEmpty(request.getParameter("estimateId"))) {
                return new ReturnResultUtil(500, MessageUtil.ESTIMATEIDNULL);
            }

            Long estimateId = Long.parseLong(request.getParameter("estimateId"));
            ReturnResultUtil rru = contractService.estimateQuantity(estimateId);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }


    @RequestMapping(value="/deviceEstimateActual",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil deviceEstimateActual(HttpServletRequest request){
        try {
            if (StringUtil.isEmpty(request.getParameter("contractDeviceId"))) {
                return new ReturnResultUtil(500, MessageUtil.CONTRACTDEVICEIDISNULL);
            }

            Long contractDeviceId = Long.parseLong(request.getParameter("contractDeviceId"));
            ReturnResultUtil rru = contractService.deviceEstimateActual(contractDeviceId);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
    }

    @RequestMapping(value="/contractExecl")
    public String contractExecl(HttpServletRequest request){
        return "contract/contract-contractExecl";
    }

    @RequestMapping(value="/contractExcel",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil contractExcel(HttpServletRequest request, HttpServletResponse response) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            String rootPath = request.getSession().getServletContext().getRealPath(File.separator);
            try {
                Long ym = new Date().getTime();
                String filePath = "upload/" + ym;
                if (files != null && files.size() > 0) {
                    for (MultipartFile m : files) {
                        if (m.getBytes().length == 0) {
                            return new ReturnResultUtil(500, MessageUtil.PLEASEUPLOADFILE);
                        }
                        String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".") + 1);
                        if (!suffix.equals("xlsx")) {
                            return new ReturnResultUtil(500, MessageUtil.FILEFORMATWRONG);
                        }
                        filePath = filePath + suffix;
                        File file = new File(rootPath + filePath);
                        if (file.exists()) {
                            file.delete();
                            file.mkdirs();
                        } else {
                            file.mkdirs();
                        }
                        m.transferTo(file);
                    }
                    User user = CacheData.getSessionUser(null,1);
                    List<Object> list = ImportExcel.excelRead(rootPath + filePath, CheckImportExcelContract.properties, ImportExcelContractModel.class);
                    CheckImportExcelContract.resultMap.put(user.getUserId(), list);
                    logger.info("==================" + JSON.toJSONString(list));
                    return new ReturnResultUtil(200, MessageUtil.UPLOADSUCCESS, list);

                } else {
                    return new ReturnResultUtil(500, MessageUtil.UPLOADFILESERROR);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return  new ReturnResultUtil(500,MessageUtil.UPLOADEXCEPTION);
    }

    @RequestMapping(value="/checkExcelContract",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil checkExcelContract(HttpServletRequest request){
        ImportExcelView importExcelView = new ImportExcelView();
        try {
            User user = CacheData.getSessionUser(null,1);
            List<ImportExcelContractModel> list =(List<ImportExcelContractModel>)CheckImportExcelContract.resultMap.get(user.getUserId());
            importExcelView = checkImportExcelContract.checkContract(list);
            return new ReturnResultUtil(200,MessageUtil.EXAMINESUCCESS,importExcelView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.EXAMINEERROR);
    }

    @RequestMapping(value="/saveContractByExecl",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveContractByExecl(HttpServletRequest request){
        try {
            User user = CacheData.getSessionUser(null, 1);
            List<ImportExcelContractModel> list = (List<ImportExcelContractModel>) CheckImportExcelContract.resultMap1.get(user.getUserId());
            ReturnResultUtil rru = contractService.saveContractByExcel(list,user);
            CheckImportExcelContract.resultMap.remove(user.getUserId());
            CheckImportExcelContract.resultMap1.remove(user.getUserId());
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }


    @RequestMapping(value="/estimateExecl")
    public String estimateExecl(HttpServletRequest request){
        return "contract/contract-estimateExecl";
    }


    @RequestMapping(value="/estimateExcel",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil estimateExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("files");
        String rootPath = request.getSession().getServletContext().getRealPath(File.separator);
        try {
            Long ym = new Date().getTime();
            String filePath = "upload/" + ym;
            if (files != null && files.size() > 0) {
                for (MultipartFile m : files) {
                    if (m.getBytes().length == 0) {
                        return new ReturnResultUtil(500, MessageUtil.PLEASEUPLOADFILE);
                    }
                    String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".") + 1);
                    if (!suffix.equals("xlsx")) {
                        return new ReturnResultUtil(500, MessageUtil.FILEFORMATWRONG);
                    }
                    filePath = filePath + suffix;
                    File file = new File(rootPath + filePath);
                    if (file.exists()) {
                        file.delete();
                        file.mkdirs();
                    } else {
                        file.mkdirs();
                    }
                    m.transferTo(file);
                }
                User user = CacheData.getSessionUser(null,1);
                List<Object> list = ImportExcel.excelRead(rootPath + filePath, CheckImportExcelEstimate.properties, ImportExcelEstimateModel.class);
                CheckImportExcelEstimate.resultMap.put(user.getUserId(), list);
                logger.info("==================" + JSON.toJSONString(list));
                return new ReturnResultUtil(200, MessageUtil.UPLOADSUCCESS, list);

            } else {
                return new ReturnResultUtil(500, MessageUtil.UPLOADFILESERROR);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  new ReturnResultUtil(500,MessageUtil.UPLOADEXCEPTION);
    }



    @RequestMapping(value="/checkExcelEstimate",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil checkExcelEstimate(HttpServletRequest request){
        ImportExcelView importExcelView = new ImportExcelView();
        try {
            User user = CacheData.getSessionUser(null,1);
            List<ImportExcelEstimateModel> list =(List<ImportExcelEstimateModel>)CheckImportExcelEstimate.resultMap.get(user.getUserId());
            importExcelView = checkImportExcelEstimate.checkEstimate(list);
            return new ReturnResultUtil(200,MessageUtil.EXAMINESUCCESS,importExcelView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.EXAMINEERROR);
    }

    @RequestMapping(value="/saveEstimateByExecl",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveEstimateByExecl(HttpServletRequest request){
        try {
            User user = CacheData.getSessionUser(null, 1);
            List<ContractEstimateSendView> cList= (List<ContractEstimateSendView>) CheckImportExcelEstimate.resultMap1.get(user.getUserId());
            ReturnResultUtil rru = contractService.saveEstimateByExecl(cList,user);
            CheckImportExcelEstimate.resultMap.remove(user.getUserId());
            CheckImportExcelEstimate.resultMap1.remove(user.getUserId());
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }
}
